/**
 * 
 */
package com.tomagency.cyberlab.server.request;

import java.io.IOException;

import javax.persistence.EntityManager;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.log4j.Logger;

import com.tomagency.cyberlab.server.config.ConfigProviderFactory;

import de.gammadata.server.requestfactory.PersistenceLocator;


/**
 * 
 * Diese Klasse dient zum Bereitstellen eines EntityManagers für die Locatoren, die für die Requestfactory benötigt werden.
 * @author gfr
 *
 */
public class EntityProviderService implements Filter {
	
//	  private static final ThreadLocal<EntityManager> ENTITY_MANAGER = new ThreadLocal<EntityManager>();
//	  
//	  /**
//	 * @return the entityManager
//	 */
//	public static EntityManager getEntityManager() {
//		return ENTITY_MANAGER.get();
//	}

	private Logger logger;

	/**
	 * 
	 */
	public EntityProviderService() {
	}

	/* (non-Javadoc)
	 * @see javax.servlet.Filter#destroy()
	 */
	@Override
	public void destroy() {
		PersistenceLocator.setEntityManager(null);
		logger=null;
	}

	/* (non-Javadoc)
	 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
	 */
	@Override
	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		EntityManager em=null;
		try {
			em=ConfigProviderFactory.getPersistenceManager().getEntityManager();
			PersistenceLocator.setEntityManager(em);		
			logger.debug("doFilter() EntityManager erzeugt");
			chain.doFilter(req, resp);
			
		}
		catch (Exception e) {
			logger.error("doFilter() Fehler: "+e.getMessage(),e);
			e.printStackTrace();
		}
		finally{
			if (em!=null&&em.isOpen())
				em.close();
			PersistenceLocator.setEntityManager(null);
			logger.debug("doFilter() EntityManager close()");
		}

	}

	/* (non-Javadoc)
	 * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
	 */
	@Override
	public void init(FilterConfig arg0) throws ServletException {
		logger = ConfigProviderFactory.getLoggingUtil().getLogger(this.getClass());
		PersistenceLocator.setEntityManager(null);

	}

}
